package com.eastfair.questionnaire.config;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ClassUtil;
import com.alibaba.fastjson.JSON;
import com.eastfair.core.utils.BeanPlusUtil;
import com.eastfair.core.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice;

import java.io.IOException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.Objects;

/**
 * @ClassName LogRequestBodyAdvice
 * @Description TODO
 * @Author yuwx
 * @Date 2021/6/16 13:22
 * @Version 1.0
 **/
@Slf4j
@ControllerAdvice
public class ProjectIdRequestBodyAdvice implements RequestBodyAdvice {
    @Override
    public boolean supports(MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }

    @Override
    public HttpInputMessage beforeBodyRead(HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) throws IOException {
        return httpInputMessage;
    }
    public static final String PROJECT_ID = "projectId";
    @Override
    public Object afterBodyRead(Object o, HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        Method method=methodParameter.getMethod();
        if (!StringUtils.isBlank(httpInputMessage.getHeaders().getFirst(PROJECT_ID))
                && !Objects.isNull(ClassUtil.getDeclaredField(o.getClass(), PROJECT_ID))) {
            BeanUtil.setFieldValue(o, PROJECT_ID, httpInputMessage.getHeaders().getFirst(PROJECT_ID));
        }
        log.info("{}.{}:{}",method.getDeclaringClass().getSimpleName(),method.getName(),JSON.toJSONString(o));
        return o;
    }

    @Override
    public Object handleEmptyBody(Object o, HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
//        Method method=methodParameter.getMethod();
//        log.info("{}.{}",method.getDeclaringClass().getSimpleName(),method.getName());
        return o;
    }
}
